package com.cc.controller;

import com.cc.allreturn.AjaxReturnBean;
import com.cc.config.YamlOtherConfiguration;
import com.cc.pojo.dto.ParametersDto;
import com.cc.pojo.dto.TableAndParameDto;
import com.cc.service.GenerateJavaService;
import com.cc.utils.JDBCUtils;
import com.cc.utils.ZipUtils;
import com.cc.utils.beanUtil.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.restart.RestartEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @User c.c
 * @Since 2023/4/19
 * @Time 18:23
 * @Description
 */
@Controller
@Slf4j
public class AutoJavaController {

  @Resource
  private GenerateJavaService generateJavaService;

  @PostMapping("/api/generate")
  @ResponseBody
  public AjaxReturnBean<String> generate(@RequestBody List<TableAndParameDto> tableAndParameDtos, HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
    httpServletResponse.reset();

    //转换成map
    Map<String, List<ParametersDto>> collect = tableAndParameDtos.stream().collect(Collectors.toMap(TableAndParameDto::getTableName, TableAndParameDto::getParametersDtoList));

    generateJavaService.generate(collect);
    log.info("生成成功！！");
    return AjaxReturnBean.createSuccess("生成成功!!!");
  }


  @GetMapping("/api/tozip")
  @ResponseBody
  public void tozip(HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
    log.info("-----------------开始下载文件-----------------");
    httpServletResponse.reset();
    YamlOtherConfiguration configurationFile = BeanUtils.getBean(YamlOtherConfiguration.class);
    File file = new File(configurationFile.getCreateAddress());
    if (!file.exists()) {
      //不存在文件
      throw new RuntimeException("不存在文件！请重新生成");
    }
    String generateAddress = configurationFile.getCreateAddress();
    // 设置response的header，response为HttpServletResponse接收输出流
    httpServletResponse.setContentType("application/zip");
    String dataBaseName = JDBCUtils.getDataBaseName().replace("'", "");
    String zipFileName = dataBaseName + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".zip";

    try {
      httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "UTF-8"));

      //生成zip
      ZipUtils.toZip(generateAddress, httpServletResponse.getOutputStream(), true);

      //删除文件
      FileUtils.deleteDirectory(new File(generateAddress));

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    log.info("-----------------文件下载结束-----------------");

  }


  @GetMapping("generate.html")
  public String getUser(Model model) {

    String dataBaseName = JDBCUtils.getDataBaseName();
    String address = JDBCUtils.getAddress();
    model.addAttribute("database", dataBaseName);
    model.addAttribute("address", address);
    return "generate";
  }


  @GetMapping("/api/isConnect")
  @ResponseBody
  public AjaxReturnBean<String> isConnect() {
    if (JDBCUtils.isConnection()) {
      return AjaxReturnBean.createSuccess("连接成功！！！");
    } else {
      return AjaxReturnBean.createError("连接失败");
    }
  }
}
